<template>
  <div class="app-container">
    <div class="top-toolbar">
      <!-- 左侧下拉查询按钮 -->
      <div class="left-buttons">
        <el-dropdown trigger="click" @visible-change="handleDropdownVisible">
          <el-button type="primary">
            所有员工 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <div style="padding: 20px; min-width: 400px">
              <el-form
                :model="queryParams"
                ref="queryRef"
                :inline="false"
                label-width="80px"
              >
                <el-form-item label="部门">
                  <el-select
                    v-model="queryParams.userdep"
                    placeholder="全部"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in deptOptions"
                      :key="item.id"
                      :label="item.departmentsName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="员工状态">
                  <el-select
                    v-model="queryParams.userstate"
                    placeholder="全部"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="在职" value="在职" />
                    <el-option label="离职" value="离职" />
                  </el-select>
                </el-form-item>
                <el-form-item label="姓名">
                  <el-input
                    v-model="queryParams.username"
                    placeholder="请输入姓名"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="入职日期">
                  <el-date-picker
                    v-model="enterDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item>
                  <div style="text-align: center">
                    <el-button type="primary" @click="handleQuery"
                      >确定</el-button
                    >
                    <el-button @click="handleDropdownClose">取消</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </el-dropdown>
      </div>

      <!-- 右侧按钮组 -->
      <div class="right-buttons">
        <el-checkbox v-model="showAllColumns">显示所有信息</el-checkbox>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['employee:employee:add']"
          >新增员工</el-button
        >
        <el-button
          type="primary"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['employee:employee:import']"
          >导入</el-button
        >
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['employee:employee:export']"
          >导出</el-button
        >
        <el-dropdown @command="handleBatchCommand">
          <el-button type="primary" plain>
            批量操作
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                command="batchDelete"
                v-hasPermi="['employee:employee:remove']"
                :disabled="multiple"
                >批量删除</el-dropdown-item
              >
              <el-dropdown-item command="batchLeave" :disabled="multiple"
                >批量离职处理</el-dropdown-item
              >
              <el-dropdown-item command="modifySalary" :disabled="multiple"
                >修改计提工资科目</el-dropdown-item
              >
              <el-dropdown-item command="modifyInsurance" :disabled="multiple"
                >批量修改五险一金</el-dropdown-item
              >
              <el-dropdown-item command="syncAuxiliary" :disabled="multiple"
                >同步至辅助核算</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button icon="Refresh" circle plain @click="getList"></el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="employeeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed />

      <!-- 始终显示的基本列，添加 fixed 属性使其固定 -->
      <el-table-column label="ID" align="center" prop="id" width="120" fixed />
      <el-table-column
        label="用户编码"
        align="center"
        prop="usercode"
        width="120"
        fixed
      />
      <el-table-column
        label="名称"
        align="center"
        prop="username"
        width="120"
        fixed
      />
      <el-table-column
        label="部门id"
        align="center"
        prop="userdep"
        width="120"
        fixed
      />

      <!-- 其他基本列 -->
      <el-table-column
        label="手机"
        align="center"
        prop="usermobile"
        width="120"
      />
      <el-table-column
        label="邮箱"
        align="center"
        prop="useremail"
        width="180"
      />
      <el-table-column
        label="身份证号"
        align="center"
        prop="useridCard"
        width="180"
      />
      <el-table-column
        label="计提科目"
        align="center"
        prop="accrualsubject"
        width="120"
      />
      <el-table-column
        label="在职状态"
        align="center"
        prop="userstate"
        width="100"
      />

      <!-- 可选显示的其他列 -->
      <template v-if="showAllColumns">
        <el-table-column
          label="性别"
          align="center"
          prop="usersex"
          width="80"
        />
        <el-table-column
          label="职务"
          align="center"
          prop="userrole"
          width="120"
        />
        <el-table-column
          label="出生日期"
          align="center"
          prop="birthday"
          width="120"
        />
        <el-table-column
          label="入职日期"
          align="center"
          prop="entertime"
          width="120"
        />
        <el-table-column
          label="离职日期"
          align="center"
          prop="leavetime"
          width="120"
        />
        <el-table-column
          label="银行名称"
          align="center"
          prop="bankname"
          width="150"
        />
        <el-table-column
          label="银行账号"
          align="center"
          prop="bankaccount"
          width="180"
        />
        <el-table-column
          label="学历"
          align="center"
          prop="degree"
          width="100"
        />
        <el-table-column label="养老保险" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.personPortion }}%</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="医疗保险" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.personPortion }}%</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="失业保险" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.personPortion }}%</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="工伤保险" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          />
        </el-table-column>
        <el-table-column label="生育保险" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          />
        </el-table-column>
        <el-table-column label="住房公积金" align="center">
          <el-table-column
            label="缴纳基数"
            align="center"
            prop="baseNum"
            width="100"
          />
          <el-table-column
            label="公司比例"
            align="center"
            prop="companyPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.companyPortion }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            label="个人比例"
            align="center"
            prop="personPortion"
            width="80"
          >
            <template #default="scope">
              <span>{{ scope.row.personPortion }}%</span>
            </template>
          </el-table-column>
        </el-table-column>
      </template>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="150"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['employee:employee:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['employee:employee:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        ref="employeeRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 基本信息 -->
        <div class="section-title">基本信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="编号" prop="usercode" required>
              <el-input v-model="form.usercode" placeholder="请输入编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="username" required>
              <el-input v-model="form.username" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="usersex" required>
              <el-select v-model="form.usersex" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="证件类型" prop="idType" required>
              <el-select v-model="form.idType" placeholder="请选择证件类型">
                <el-option label="居民身份证" value="居民身份证" />
                <el-option label="中国护照" value="中国护照" />
                <el-option
                  label="港澳居民来往内地通行证"
                  value="港澳居民来往内地通行证"
                />
                <el-option
                  label="台湾居民来往内地通行证"
                  value="台湾居民来往内地通行证"
                />
                <el-option label="港澳居民居住证" value="港澳居民居住证" />
                <el-option label="台湾居民居住证" value="台湾居民居住证" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证件号码" prop="useridCard" required>
              <el-input
                v-model="form.useridCard"
                placeholder="请输入证件号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="请选择出生日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机" prop="usermobile" required>
              <el-input v-model="form.usermobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="useremail">
              <el-input v-model="form.useremail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学历" prop="degree">
              <el-select
                v-model="form.degree"
                placeholder="请选择学历"
                default-first-option
              >
                <el-option label="小学" value="小学" />
                <el-option label="初中" value="初中" />
                <el-option label="高中" value="高中" />
                <el-option label="中专" value="中专" />
                <el-option label="大专" value="大专" />
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="银行名称" prop="bankname">
              <el-input v-model="form.bankname" placeholder="请输入银行名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行账号" prop="bankaccount">
              <el-input
                v-model="form.bankaccount"
                placeholder="请输入银行账号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="部门" prop="userdep" required>
              <el-select
                v-model="form.userdep"
                placeholder="请选择部门"
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptOptions"
                  :key="item.id"
                  :label="item.departmentsName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职位" prop="userrole">
              <el-input v-model="form.userrole" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="员工状态" prop="userstate" required>
              <el-select v-model="form.userstate" placeholder="在职">
                <el-option label="在职" value="在职" />
                <el-option label="离职" value="离职" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计提工资科目" prop="accrualsubject" required>
              <el-select v-model="form.accrualsubject" placeholder="请选择">
                <el-option
                  label="5601016销售费用-业务宣传费"
                  value="5601016销售费用-业务宣传费"
                />
                <el-option
                  label="5602001管理费用-管理人员职工薪酬"
                  value="5602001管理费用-管理人员职工薪酬"
                />
                <el-option label="5602007管理员工" value="5602007管理员工" />

                <!-- 添加更多科目选项 -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入职日期" prop="entertime" required>
              <el-date-picker
                v-model="form.entertime"
                type="date"
                placeholder="请选择入职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工资起发日期" prop="salaryStartDate">
              <el-date-picker
                v-model="form.salaryStartDate"
                type="date"
                placeholder="请选择工资起发日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 扣除款项 -->
        <div class="section-title">扣除款项</div>
        <el-form-item label="是否缴纳五险一金" prop="whether" required>
          <el-radio-group v-model="form.whether">
            <el-radio :value="'是'">是</el-radio>
            <el-radio :value="'否'">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 五险一金表格 -->
        <el-table
          :data="socialsecurityList"
          v-if="form.whether === '是'"
          border
        >
          <el-table-column label="项目" prop="project" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.project" disabled />
            </template>
          </el-table-column>
          <el-table-column label="缴纳基数" prop="baseNum" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.baseNum" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="公司承担部分" align="center">
            <el-table-column
              label="公司缴纳比例"
              prop="companyPortion"
              align="center"
              width="120"
            >
              <template #default="scope">
                <div class="percentage-input">
                  <el-input
                    v-model="scope.row.companyPortion"
                    placeholder="请输入"
                  />
                  <span class="percentage-symbol">%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="公司缴纳金额"
              prop="companyPay"
              align="center"
              width="120"
            >
              <template #default="scope">
                <el-input v-model="scope.row.companyPay" disabled />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="个人承担部分" align="center">
            <el-table-column
              label="个人缴纳比例"
              prop="personPortion"
              align="center"
              width="120"
            >
              <template #default="scope">
                <div class="percentage-input">
                  <el-input
                    v-model="scope.row.personPortion"
                    placeholder="请输入"
                    :disabled="
                      scope.row.project === '工伤保险' ||
                      scope.row.project === '生育保险'
                    "
                  />
                  <span class="percentage-symbol">%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="个人缴纳金额"
              prop="personPay"
              align="center"
              width="120"
            >
              <template #default="scope">
                <el-input v-model="scope.row.personPay" disabled />
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog
      title="员工信息导入"
      v-model="importOpen"
      width="500px"
      append-to-body
    >
      <div class="import-content">
        <div class="step">
          <div class="step-title">1.请选择下面任意一种方式导入员工信息</div>
          <div class="step-options">
            <div class="option">
              (1)在员工信息列表导出所需数据，确认后直接导入
            </div>
            <div class="option">
              (2)点击<el-link
                type="primary"
                :underline="false"
                @click="handleDownloadTemplate"
                >下载模板</el-link
              >，按照模板格式式进行数据整理再导入
            </div>
          </div>
        </div>

        <div class="step">
          <div class="step-title">2.选择文件导入</div>
          <div class="step-options">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="https://127.0.0.1:10010/employee/emloyee/Import"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">选取文件</el-button>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500kb
                </div>
              </template>
            </el-upload>
            <!-- <el-link type="primary" :underline="false" @click="handleSelectFile"
              >选取文件</el-link
            > -->
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleImportSubmit"
            >导 入</el-button
          >
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加批量离职对话框 -->
    <el-dialog
      title="批量离职处理"
      v-model="batchLeaveOpen"
      width="500px"
      append-to-body
    >
      <el-form
        :model="leaveForm"
        ref="leaveFormRef"
        :rules="leaveRules"
        label-width="100px"
      >
        <el-form-item label="员工状态" prop="userstate" required>
          <el-input
            v-model="leaveForm.userstate"
            disabled
            placeholder="离职状态"
          />
        </el-form-item>
        <el-form-item label="离职日期" prop="leavetime" required>
          <el-date-picker
            v-model="leaveForm.leavetime"
            type="date"
            placeholder="请选择离职日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLeaveForm">确 定</el-button>
          <el-button @click="cancelLeave">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加修改计提工资科目对话框 -->
    <el-dialog
      title="修改计提工资科目"
      v-model="modifySalaryOpen"
      width="500px"
      append-to-body
    >
      <el-form
        :model="salaryForm"
        ref="salaryFormRef"
        :rules="salaryRules"
        label-width="100px"
      >
        <el-form-item label="计提工资科目" prop="accrualsubject" required>
          <el-select
            v-model="salaryForm.accrualsubject"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              label="销售费用-业务宣传费"
              value="销售费用 - 业务宣传费"
            />
            <el-option
              label="管理费用-管理人员职工薪酬"
              value="管理费用 - 管理人员职工薪酬"
            />
            <el-option label="5602007管理员工" value="5602007管理员工" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSalaryForm">确 定</el-button>
          <el-button @click="cancelSalary">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employee">
import {
  listEmployee,
  getEmployee,
  delEmployee,
  addEmployee,
  updateEmployee,
  Import,
  batchLeave,
  updateAccrualsubject,
} from "@/api/employee/employee";
import { optionDepartments } from "@/api/employee/departments";
import { ArrowDown } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

const employeeList = ref([]);
const socialsecurityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedSocialsecurity = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    userdep: null,
    enterStartTime: null,
    enterEndTime: null,
    leavetime: null,
    userstate: null,
  },
  rules: {
    usercode: [
      { required: true, message: "用户编码不能为空", trigger: "blur" },
    ],
    username: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    usersex: [{ required: true, message: "性别不能为空", trigger: "change" }],
    userdep: [{ required: true, message: "部门id不能为空", trigger: "change" }],
    userrole: [{ required: true, message: "职务不能为空", trigger: "blur" }],
    usermobile: [{ required: true, message: "手机不能为空", trigger: "blur" }],
    useridCard: [
      { required: true, message: "身份证号不能为空", trigger: "blur" },
    ],
    useremail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
    entertime: [
      { required: true, message: "入职日期不能为空", trigger: "blur" },
    ],
    leavetime: [
      { required: true, message: "离职日期不能为空", trigger: "blur" },
    ],
    userstate: [
      { required: true, message: "在职状态不能为空", trigger: "blur" },
    ],
    accrualsubject: [
      { required: true, message: "计提科目不能为空", trigger: "blur" },
    ],
    accountSetsId: [
      { required: true, message: "所属账套不能为空", trigger: "blur" },
    ],
    whether: [
      {
        required: true,
        message: "是否缴纳五险一金不能为空",
        trigger: "change",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 添加搜索相关的响应式变量
const searchType = ref("");
const searchValue = ref("");

// 获取输入框的 placeholder
const getPlaceholder = computed(() => {
  switch (searchType.value) {
    case "name":
      return "请输入员工姓名";
    case "workNumber":
      return "请输入工号";
    case "departmentName":
      return "请输入部门名称";
    default:
      return "";
  }
});

// 处理下拉菜单选择
const handleSearch = (command) => {
  searchType.value = command;
  searchValue.value = "";
};

// 日期范围
const dateRange = ref([]);

// 添加入职日期范围变量
const enterDateRange = ref([]);

// 添加控制列显示的响应式变量
const showAllColumns = ref(false);

// 添加下拉框控制变量
const dropdownVisible = ref(false);
const importOpen = ref(false);

// 添加部门选项的响应式变量
const deptOptions = ref([]);
const modifySalaryOpen = ref(false);

// 获取部门列表
function getDeptList() {
  optionDepartments().then((response) => {
    deptOptions.value = response;
  });
}

// 处理下拉框显示状态变化
function handleDropdownVisible(visible) {
  dropdownVisible.value = visible;
}

// 关闭下拉框
function handleDropdownClose() {
  dropdownVisible.value = false;
}

/** 查询员工信息列表 */
function getList() {
  loading.value = true;
  listEmployee(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      employeeList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    usercode: null,
    username: null,
    usersex: null,
    userdep: null,
    userrole: null,
    usermobile: null,
    useridCard: null,
    useremail: null,
    birthday: null,
    entertime: null,
    leavetime: null,
    bankname: null,
    bankaccount: null,
    degree: "其他",
    userstate: null,
    accrualsubject: null,
    accountSetsId: null,
    note: null,
    whether: "是",
    idType: "居民身份证",
  };
  initSocialSecurityList(); // 初始化五险一金数据
  proxy.resetForm("employeeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  // 处理入职日期范围
  if (enterDateRange.value && enterDateRange.value.length === 2) {
    queryParams.value.enterStartTime = enterDateRange.value[0];
    queryParams.value.enterEndTime = enterDateRange.value[1];
  } else {
    queryParams.value.enterStartTime = undefined;
    queryParams.value.enterEndTime = undefined;
  }

  getList();
  dropdownVisible.value = false; // 查询后关闭下拉框
}

/** 重置按钮操作 */
function resetQuery() {
  enterDateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加员工信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getEmployee(_id).then((response) => {
    form.value = response.data;
    socialsecurityList.value = response.data.socialsecurityList;
    open.value = true;
    title.value = "修改员工信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeeRef"].validate((valid) => {
    if (valid) {
      form.value.socialsecurityList = socialsecurityList.value;
      if (form.value.id != null) {
        updateEmployee(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEmployee(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row ? row.id : ids.value.join(",");
  if (!_ids) {
    proxy.$modal.msgError("请选择要删除的员工");
    return;
  }
  proxy.$modal
    .confirm('是否确认删除员工信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delEmployee(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 五险一金序号 */
function rowSocialsecurityIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 五险一金添加按钮操作 */
function handleAddSocialsecurity() {
  let obj = {};
  obj.project = "";
  obj.baseNum = "";
  obj.companyPortion = "";
  obj.companyPay = "";
  obj.personPortion = "";
  obj.personPay = "";
  socialsecurityList.value.push(obj);
}

/** 五险一金删除按钮操作 */
function handleDeleteSocialsecurity() {
  if (checkedSocialsecurity.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的五险一金数据");
  } else {
    const socialsecuritys = socialsecurityList.value;
    const checkedSocialsecuritys = checkedSocialsecurity.value;
    socialsecurityList.value = socialsecuritys.filter(function (item) {
      return checkedSocialsecuritys.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleSocialsecuritySelectionChange(selection) {
  checkedSocialsecurity.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "employee/employee/export",
    {
      ...queryParams.value,
    },
    `employee_${new Date().getTime()}.xlsx`
  );
}

/** 处理批量操作命令 */
function handleBatchCommand(command) {
  switch (command) {
    case "batchDelete":
      handleDelete();
      break;
    case "batchLeave":
      handleBatchLeave();
      break;
    case "modifySalary":
      handleModifySalary();
      break;
    case "modifyInsurance":
      handleModifyInsurance();
      break;
    case "syncAuxiliary":
      handleSyncAuxiliary();
      break;
  }
}

/** 批量离职处理 */
function handleBatchLeave() {
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgError("请选择要处理的员工");
    return;
  }
  batchLeaveOpen.value = true;
}

/** 修改计提工资科目 */
function handleModifySalary() {
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgError("请选择要处理的员工");
    return;
  }
  modifySalaryOpen.value = true;
}

/** 批量修改五险一金 */
function handleModifyInsurance() {
  // TODO: 实现批量修改五险一金逻辑
  proxy.$modal.msgInfo("批量修改五险一金功能待实现");
}

/** 同步至辅助核算 */
function handleSyncAuxiliary() {
  // TODO: 实现同步至辅助核算逻辑
  proxy.$modal.msgInfo("同步至辅助核算功能待实现");
}

// 初始化五险一金数据
function initSocialSecurityList() {
  socialsecurityList.value = [
    {
      project: "养老保险",
      baseNum: "",
      companyPortion: "20",
      companyPay: "0.00",
      personPortion: "8",
      personPay: "0.00",
    },
    {
      project: "医疗保险",
      baseNum: "",
      companyPortion: "10",
      companyPay: "0.00",
      personPortion: "2",
      personPay: "0.00",
    },
    {
      project: "失业保险",
      baseNum: "",
      companyPortion: "1",
      companyPay: "0.00",
      personPortion: "0.2",
      personPay: "0.00",
    },
    {
      project: "工伤保险",
      baseNum: "",
      companyPortion: "0.5",
      companyPay: "0.00",
      personPortion: "", // 工伤保险个人不缴纳
      personPay: "", // 工伤保险个人不缴纳
    },
    {
      project: "生育保险",
      baseNum: "",
      companyPortion: "0.8",
      companyPay: "0.00",
      personPortion: "", // 生育保险个人不缴纳
      personPay: "", // 生育保险个人不缴纳
    },
    {
      project: "住房公积金",
      baseNum: "",
      companyPortion: "12",
      companyPay: "0.00",
      personPortion: "12",
      personPay: "0.00",
    },
  ];
}

// 监听缴纳基数变化，自动计算金额
watch(
  () => socialsecurityList.value,
  (list) => {
    list.forEach((item) => {
      if (item.baseNum && item.companyPortion) {
        item.companyPay = ((item.baseNum * item.companyPortion) / 100).toFixed(
          2
        );
      }
      if (item.baseNum && item.personPortion) {
        item.personPay = ((item.baseNum * item.personPortion) / 100).toFixed(2);
      }
    });
  },
  { deep: true }
);

/** 导入按钮操作 */
function handleImport() {
  importOpen.value = true;
}

/** 下载模板 */
function handleDownloadTemplate() {
  proxy.download(
    "employee/employee/importTemplate",
    {},
    `employee_template_${new Date().getTime()}.xlsx`
  );
}

/** 选择文件 */
function handleSelectFile() {
  // TODO: 实现文件选择逻辑
}

/** 提交导入 */
function handleImportSubmit() {
  // TODO: 实现导入提交逻辑
}

/** 取消导入 */
function cancelImport() {
  importOpen.value = false;
}

// 添加批量离职相关的响应式变量
const batchLeaveOpen = ref(false);
const leaveFormRef = ref();
const leaveForm = ref({
  userstate: "离职",
  leavetime: "",
  salaryEndDate: "",
});

// 添加离职表单验证规则
const leaveRules = {
  leavetime: [{ required: true, message: "离职日期不能为空", trigger: "blur" }],
  salaryEndDate: [
    { required: true, message: "工资停发日期不能为空", trigger: "blur" },
  ],
};

/** 取消离职 */
function cancelLeave() {
  batchLeaveOpen.value = false;
  leaveForm.value = {
    userstate: "离职",
    leavetime: "",
    salaryEndDate: "",
  };
}

/** 提交离职表单 */
function submitLeaveForm() {
  leaveFormRef.value.validate((valid) => {
    if (valid) {
      batchLeave(ids.value).then((response) => {
        proxy.$modal.msgSuccess("批量离职处理成功");
        batchLeaveOpen.value = false;
        getList();
      });
    }
  });
}

// 添加修改计提工资科目相关的响应式变量

const salaryFormRef = ref();
const salaryForm = ref({
  accrualsubject: "",
});

// 添加表单验证规则
const salaryRules = {
  accrualsubject: [
    { required: true, message: "计提工资科目不能为空", trigger: "change" },
  ],
};

/** 提交修改计提工资科目表单 */
function submitSalaryForm() {
  let kemu = salaryForm.value.accrualsubject;
  console.log(kemu);
  salaryFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用修改计提工资科目的API
      updateAccrualsubject(ids.value, kemu).then((response) => {
        proxy.$modal.msgSuccess("修改计提工资科目成功");
        modifySalaryOpen.value = false;
        getList();
      });
    }
  });
}

/** 取消修改计提工资科目 */
function cancelSalary() {
  modifySalaryOpen.value = false;
  salaryForm.value = {
    accrualsubject: "",
  };
}

//钩子函数
onMounted(() => {
  getDeptList();
  getList();
});
</script>

<style scoped>
.top-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.right-buttons {
  display: flex;
  align-items: center;
  gap: 8px; /* 按钮之间的间距 */
}

.right-buttons .el-checkbox {
  margin-right: 16px;
}

/* 移除原有的一些样式 */
.toolbar-wrapper {
  margin-top: 0;
}

/* 保留其他必要的样式 */
:deep(.el-dropdown-menu__item) {
  padding: 0;
  margin: 0;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100%;
}

/* 添加新的样式 */
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-form-item.is-required .el-form-item__label:before) {
  color: #ff4949;
}

/* 添加新的样式 */
.percentage-input {
  position: relative;
  display: flex;
  align-items: center;
}

.percentage-symbol {
  position: absolute;
  right: 5px;
  color: #606266;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #f5f7fa;
}

.import-content {
  padding: 20px;
}

.step {
  margin-bottom: 20px;
}

.step-title {
  font-size: 14px;
  margin-bottom: 10px;
}

.step-options {
  padding-left: 20px;
}

.option {
  line-height: 24px;
  margin-bottom: 8px;
}

:deep(.el-link) {
  font-size: 14px;
}

:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

/* 添加离职对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px 40px;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
}
</style>
